# blog_manager.py
from database import *
from models import *

class BlogManager:
    """
    博客管理器类，用于管理博客系统的用户和文章操作

    Attributes:
        conn: 数据库连接对象
    """
    def __init__(self, db_path: str):
        """
        初始化博客管理器

        Args:
            db_path (str): 数据库文件路径
        """
        self.conn = get_connection(db_path)
        init_database(self.conn)

    def create_user(self, username: str, email: str) -> bool:
        """
          创建新用户

          Args:
              username (str): 用户名
              email (str): 用户邮箱

          Returns:
              bool: 创建成功返回True，失败返回False
          """
        return safe_execute(
            self.conn,
            "INSERT INTO users (username, email) VALUES (?, ?)",
            (username, email)
        )

    def user_is_exist(self, author_id: int):
        """
        判断用户是否存在
        """
        return execute_query(self.conn, "SELECT * FROM users WHERE id = ?",(author_id,))

    def create_post(self, title: str, content: str, author_id: int) -> bool:
        """
        创建新文章

        Args:
            title (str): 文章标题
            content (str): 文章内容
            author_id (int): 作者ID

        Returns:
            bool: 创建成功返回True，失败返回False
        """
        return safe_execute(
            self.conn,
            "INSERT INTO posts (title, content, author_id) VALUES (?, ?, ?)",
            (title, content, author_id)
        )

    def get_posts_by_author(self, author_id: int) -> List[Dict]:
        """
        获取指定作者的所有文章，包含作者信息

        Args:
            author_id (int): 作者ID

        Returns:
            List[Dict]: 文章列表，每篇文章包含作者用户名和文章信息
        """
        query = """
        SELECT p.*, u.username as author_name
        FROM posts p
        JOIN users u ON p.author_id = u.id
        WHERE p.author_id like ?
        OR u.username like ?
        ORDER BY p.created_at DESC
        """
        return execute_query(self.conn, query, (f'{author_id}',f'{author_id}'))

    def search_posts(self, keyword: str = None, author_id: int = None) -> List[Dict]:
        """搜索文章，支持关键词和作者筛选"""
        query = """
        SELECT p.*, u.username as author_name
        FROM posts p
        JOIN users u ON p.author_id = u.id
        WHERE 1=1
        """
        params = []

        if keyword:
            query += " AND (p.title LIKE ? OR p.content LIKE ?)"
            params.extend([f'%{keyword}%', f'%{keyword}%'])
        if author_id:
            query += " AND p.author_id = ?"
            params.append(author_id)
        query += " ORDER BY p.created_at DESC"
        return execute_query(self.conn, query, tuple(params))